package jwlee.testnetwork;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class ClientDemo implements Runnable {

	private String name = "";

	private String host = "localhost";

	private int port = 8888;

	Socket socket = null;

	public ClientDemo() {
	}

	public ClientDemo(String name, String host, int port) {
		this.name = name;
		if (host != null)
			this.host = host;
		this.port = port;
	}

	public static void main(String[] args) {
		new Thread(new ClientDemo("zhang3", null, 7777)).start();
		new Thread(new ClientDemo("li4", null, 8888)).start();
		new Thread(new ClientDemo("wang5", null, 8888)).start();
	}

	public void run() {
		try {
			this.socket = new Socket(this.host, this.port);
			this.socket.setSoTimeout(10000);// 设置10秒之后即认为超时

			// this.socket = new Socket();
			// this.socket.connect(new InetSocketAddress(host, port) ,10000);

			// 获取输出流，用于客户端向服务器端发送数据
			DataOutputStream dos = new DataOutputStream(this.socket
					.getOutputStream());
			// 获取输入流，用于接收服务器端发送来的数据
			DataInputStream dis = new DataInputStream(this.socket
					.getInputStream());

			// 客户端向服务器端发送数据
			dos.writeUTF("我是客户端" + this.name + "，请求连接!");

			// 打印出从服务器端接收到的数据
			System.out.println("Message from Server: " + dis.readUTF());
		} catch (Exception e) {
			e.printStackTrace();
			try {
				if (this.socket != null && !this.socket.isClosed()) {
					this.socket.close();
				}
				Thread.sleep(5000);// 关闭服务后睡眠5s.
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
}
